from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse
from get_data.models import ContentInfo, CommentInfo
from user_abt.models import UserInfo, Session_Self
# Create your views here.
from return_data.return_data import return_data
import json
import requests
import oss2
import time
from anytools.oss_config import up_to_oss


@require_http_methods(['OPTIONS','GET'])
def find_index(request):
    if request.method == 'GET':
        content_type = request.GET.get("content_type")
        session_id = request.GET.get('session_id')
        if session_id:
            session_id = session_id.strip("\"")
        data_lenth = int(request.GET.get("data_lenth"))
        # 一次最多返回10个文章信息
        if content_type:
            contents = ContentInfo.objects.filter(content_type=content_type).all()[data_lenth:data_lenth+10]
        elif session_id:
            content_auth_id = Session_Self.objects.filter(sessionid=session_id).first().userid
            contents = ContentInfo.objects.filter(content_auth_id=content_auth_id).all()[data_lenth:data_lenth+10]

        data = []
        if contents:
            for content in contents:
                id = content.id
                image = content.content_image.split(',')[0]
                title = content.content_name
                goods = content.content_star_number
                writer_id = content.content_auth_id
                intro = content.content_intro

                user = UserInfo.objects.filter(id=writer_id).first()
                if user:
                    writer_image = user.user_image
                    writer_name = user.user_name
                else:
                    writer_name = "查无此人"
                    writer_image = "https://gaf.oss-cn-beijing.aliyuncs.com/user_image/house.png"
                content_info = {"content_id":id, "image":image, "title":title, "goods":goods, 
                                "writer_image":writer_image, "writer_name":writer_name, "intro":intro}
                data.append(content_info)
            ret = return_data(0, "ok", data)
        else:
            ret = return_data(-1, "no more data", [])
        return HttpResponse(ret, content_type="application/json,charset=utf-8")
    else:
        return HttpResponse(200)

@require_http_methods(['OPTIONS', 'GET'])
def get_content(request):
    if request.method == "GET":
        content_id = request.GET.get('content_id')
        content = ContentInfo.objects.filter(id=content_id).first()

        if content:
            image = content.content_image.split(',')
            print(type(image))
            title = content.content_name
            goods = content.content_star_number
            content_text = content.content_text
            writer_id = content.content_auth_id
            user = UserInfo.objects.filter(id=writer_id).first()
            if user:
                writer_image = user.user_image
                writer_name = user.user_name
            else:
                writer_name = "查无此人"
                writer_image = "https://gaf.oss-cn-beijing.aliyuncs.com/user_image/house.png"
            content_info = {"image":image, "title":title, "goods":goods, "content_text":content_text, 
                            "writer_name":writer_name, "writer_image":writer_image}
            ret = return_data(0, "get", content_info)
        else:
            ret = return_data(-1, "content no find", [])
        return HttpResponse(ret, content_type="application/json,charset=utf-8")
    else:
        return HttpResponse(200)

@require_http_methods(['OPTIONS', 'GET'])
def weather(request):
    if request.method == "GET":
        bdak = "gn8DBuXwo5IkEPosI11yYLoPELj1iA6E"
        gdkey = "43f4d1a08835d3028cab5004363f9e9b"
        ip = request.GET.get('ip')
        res = requests.get("http://api.map.baidu.com/location/ip", params={
            "ak":bdak,
            "ip":ip,
            "coor":"bd09ll"
        })
        locations_info = json.loads(res.text)['content']['address']

        res = requests.get("https://restapi.amap.com/v3/geocode/geo", params={
            "address":locations_info,
            "key":gdkey,
        })
        adcode = json.loads(res.text)['geocodes'][0]['adcode']

        res = requests.get("https://restapi.amap.com/v3/weather/weatherInfo", params={
            "key":gdkey,
            "city":adcode,
            "extensions":"all",
        })
        weather = json.loads(res.text)['forecasts'][0]['casts']
        data = {"locations_info":locations_info, "weather":weather}
        ret = return_data(0, "ok", data)
        return HttpResponse(ret, content_type="application/json,charset=utf-8")
    else:
        return HttpResponse(200)

@require_http_methods(['OPTIONS', 'POST'])
def up_content(request):
    if request.method == "POST":
        session_id = request.POST.get('session_id').strip("\"")
        # print(session_id, type(session_id))
        # print("1")
        content_auth_id = Session_Self.objects.filter(sessionid=session_id).first().userid
        # print(content_auth_id)
        content_intro = request.POST.get('content_intro')
        print(content_intro)
        content_id = request.POST.get('id')
        title = request.POST.get('title')
        content_type = request.POST.get('type')
        content_text = request.POST.get('content_text')
        imags = request.FILES.getlist('imags')
        imags_oss = ""
        if imags:
            times = 1
            for i in imags:
                imags_name = str(time.time())+"("+str(times)+")."+i.name.split('.')[-1]
                up_pic_ret = up_to_oss('gaf', r"content_image/{0}".format(imags_name), i.file)
                if times == 1:
                    imags_oss = imags_oss + "https://gaf.oss-cn-beijing.aliyuncs.com/content_image/" + imags_name
                else:
                    imags_oss = imags_oss + ',' + "https://gaf.oss-cn-beijing.aliyuncs.com/content_image/" + imags_name
                times += 1
        else:
            pass
        if content_id:
            content = ContentInfo.objects.filter(id=content_id).first()
        else:
            content = ContentInfo()
        content.content_name = title
        content.content_intro = content_intro
        content.content_auth_id = content_auth_id
        content.content_text = content_text
        content.content_type = content_type
        content.content_image = imags_oss
        content.save()

        return HttpResponse(200)
    else:
        return HttpResponse(200)
